<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form :inline="true" :model="user" ref="form">
        <el-form-item label="userId" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="userName" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="state" prop="state">
          <el-select v-model="user.state" placeholder="请选择">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <div>
          <el-button type="primary" size="mini" @click="handleCreate" v-has="'user-add'">新增</el-button>
          <el-button type="danger" size="mini" @click="handleBatchDelete" v-has="'user-batchDelete'">批量删除</el-button>
        </div>
        <el-table 
          :data="userList" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column  type="selection" width="55" />
          <el-table-column 
            v-for="item in columns" 
            :key="item.prop" 
            :label="item.label" 
            :prop="item.prop" 
            width="180" 
            :formatter="item.formatter"
          />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          background 
          layout="prev, pager, next" 
          :total="pager.total" 
          class="pagination" 
          @current-change="handleCurrentChange"
          />
      </div>
    </div>
    <el-dialog
      :title="action==='add'?'用户新增':'编辑用户'"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        :model="userForm"
        label-width="120px"
        ref="dialogForm"
        :rules="rules"
      >
        <el-form-item prop="userName" label="用户名">
          <el-input
            placeholder="请输入用户名称"
            v-model="userForm.userName"
            :disabled="action == 'edit'"
          />
        </el-form-item>
        <el-form-item prop="userEmail" label="邮箱">
          <el-input
            placeholder="请输入用户邮箱"
            v-model="userForm.userEmail"
            :disabled="action == 'edit'"
          >
            <template #append> @jason.com </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input placeholder="请输入手机号" v-model="userForm.mobile" />
        </el-form-item>
        <el-form-item prop="job" label="岗位">
          <el-input placeholder="请输入岗位" v-model="userForm.job" />
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-select v-model="userForm.state">
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="roleList" label="系统角色">
          <el-select
            v-model="userForm.roleList"
            placeholder="请选择用户角色"
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList.list"
              :key="role._id"
              :label="role.roleName"
              :value="role._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deptId" label="部门">
          <el-cascader
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/* vue3写法 */
import { onMounted, reactive, getCurrentInstance, ref, toRaw } from 'vue'
export default {
  name: 'User',
  setup() {
    const { proxy } = getCurrentInstance()
    onMounted(() => {
      getUserList()
      getRoleList()
      getDeptList()
    })
    const user = reactive({
      userId: '',
      userName: '',
      state: 0
    })
    const userList = ref([])
    const columns = reactive([
      {label: '用户ID', prop: 'userId'},
      {label: '用户名', prop: 'userName'},
      {label: '用户邮箱', prop: 'userEmail'},
      {label: '用户邮箱', prop: 'userEmail'},
      {
        label: '用户角色', 
        prop: 'role', 
        formatter(row, column, value) {
          return {
            0: '管理员',
            1: '普通用户'
          }[value]
        }
      },
      {
        label: '用户状态', 
        prop: 'state',
        formatter(row, column, value) {
          return {
            1: '在职',
            2: '离职',
            3: '试用期'
          }[value]
        }
      },
      {label: '注册时间', prop: 'createTime'},
      {label: '最后登录时间', prop: 'lastLoginTime'},
    ])
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 10
    })
    const getUserList = async () => {
      const params = {...user, ...pager}
      // proxy 类似于 this
      const { page, list } = await proxy.$api.userList(params)
      pager.total = page.total
      userList.value = list
    }
    const handleQuery = () => {
      getUserList()
    }
    const handleReset = (form) => {
      proxy.$refs[form].resetFields()
    }
    const handleCurrentChange = (current) => {
      pager.pageNum = current
      getUserList()
    }
    const handleDelete = async (row) => {
      console.log(row);
      if(row.role === '管理员') {
        proxy.$message.error('不支持删除管理员')
        return
      }
      const res = await proxy.$api.userDelete({userIds: [row.userId]})
      if(res.modifiedCount > 0) {
        proxy.$message.success('删除成功')
        getUserList()
      } else{
        proxy.$message.error('删除失败')
      }
    }
    const checkedUserIds = ref([])
    const handleBatchDelete = async () => {
      if(checkedUserIds.value.length === 0) {
        proxy.$message.error('请选择要删除的用户')
        return
      }
      const res = await proxy.$api.userDelete({userIds: checkedUserIds.value})
      if(res.modifiedCount > 0) {
        proxy.$message.success('删除成功')
        getUserList()
      } else{
        proxy.$message.error('删除失败')
      }
    }
    const handleSelectionChange = (list) => {
      if(list.find(item => item.role === '管理员')) {
        proxy.$message.error('不支持删除管理员')
        return
      }
      let arr = []
      list.forEach(item => {
        arr.push(item.userId)
      });
      checkedUserIds.value = arr
    }
    const showModal = ref(false)
    const handleCreate = () => {
      showModal.value = true
    }
    let action = ref('add')
    const userForm = reactive({})
    const rules = reactive({
      userName: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }
      ]
    })
    const roleList = ref([])
    const getRoleList = async () => {
      const res = await proxy.$api.getRoleList()
      roleList.value = res
      
    }
    const deptList = ref([])
    const getDeptList = async () => {
      const res = await proxy.$api.getDeptList()
      deptList.value = res
    }
    const handleClose = () => {
      showModal.value = false
      handleReset('dialogForm')
    }
    const handleSubmit = async () => {
      proxy.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let params = toRaw(userForm);
          params.userEmail += "@jason.com";
          params.action = action.value;
          let res = await proxy.$api.userSubmit(params);
          if (res) {
            showModal.value = false;
            proxy.$message.success("新增用户成功");
            handleReset("dialogForm");
            getUserList();
          }
        }
      });
    }
    const handleEdit = async (row) => {
      action.value = 'edit'
      showModal.value = true
      proxy.$nextTick(() => {
        row.state = Number(row.state);
        Object.assign(userForm, row)
      })
    }
    return  {
      user,
      userList,
      columns,
      handleQuery,
      handleReset,
      pager,
      handleCurrentChange,
      handleDelete,
      handleBatchDelete,
      checkedUserIds,
      handleSelectionChange,
      showModal,
      handleCreate,
      userForm,
      action,
      rules,
      roleList,
      deptList,
      getRoleList,
      getDeptList,
      handleClose,
      handleSubmit,
      handleEdit
    }
  }
}
</script>